package school.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import school.domain.Info;
import school.domain.Life;
import school.domain.Message;
import school.domain.Personal;
import school.mapper.InfoMapper;
import school.mapper.LifeMapper;
import school.mapper.MessageMapper;
import school.mapper.PersonalMapper;
import school.support.BaseController;
import school.support.pojo.InfoPo;
import school.support.util.ParamUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;

@RequestMapping("info")
@Controller
public class InfoController extends BaseController {

    @Autowired
    private InfoMapper infoMapper;
    @Autowired
    private MessageMapper messageMapper;
    @Autowired
    private LifeMapper lifeMapper;
    @Autowired
    private PersonalMapper personalMapper;

    /**
     * 列表
     *
     * @param info
     * @param pageNum
     * @param model
     * @return
     */
    @RequestMapping("list")
    public String list(InfoPo info, @RequestParam(defaultValue = "1") Integer pageNum, Model model) {
        Example example = new Example(Info.class);
        Example.Criteria criteria = example.createCriteria();
        if (info.getName() != null) {
            criteria.andCondition("name like '%" + info.getName() + "%'");
        }

        /**
         * 如果是普通用户   只能看到自己的
         */
        if (sessionUser().getType().equalsIgnoreCase("user")) {
            criteria.andEqualTo("userid", sessionUser().getId());
        }
        /**
         * 如果是医生     只能看到自己负责的用户
         */
        if (sessionUser().getType().equalsIgnoreCase("doctor")) {
            criteria.andCondition("u.doctor = '" + sessionUser().getId() + "'");
        }

        PageHelper.startPage(pageNum, pageSize);
        PageInfo<InfoPo> pageInfo = new PageInfo<>(infoMapper.selectPoByExample(example), 5);
        model.addAttribute(pageInfo);
        model.addAttribute("url", request.getRequestURI() + "?" + ParamUtils.params2String(request));
        return "info/list";
    }

    @RequestMapping("listT")
    public String listT(InfoPo info, @RequestParam(defaultValue = "1") Integer pageNum, Model model) {
        Example example = new Example(Info.class);
        Example.Criteria criteria = example.createCriteria();
        if (info.getName() != null) {
            criteria.andCondition("name like '%" + info.getName() + "%'");
        }

        /**
         * 如果是普通用户   只能看到自己的
         */
        if (sessionUser().getType().equalsIgnoreCase("user")) {
            criteria.andEqualTo("userid", sessionUser().getId());
        }
        /**
         * 如果是医生     只能看到自己负责的用户
         */
        if (sessionUser().getType().equalsIgnoreCase("doctor")) {
            criteria.andCondition("u.doctor = '" + sessionUser().getId() + "'");
        }

        PageHelper.startPage(pageNum, pageSize);
        PageInfo<InfoPo> pageInfo = new PageInfo<>(infoMapper.selectPoByExample(example), 5);
        model.addAttribute(pageInfo);
        model.addAttribute("url", request.getRequestURI() + "?" + ParamUtils.params2String(request));
        return "info/listT";
    }

    @RequestMapping("detail/{id}")
    public String detail(@PathVariable Integer id, Model model) {
        Info info = infoMapper.selectByPrimaryKey(id);
        model.addAttribute(info);
        return "info/detail";
    }

    /**
     * 修改信息
     *
     * @param info
     * @return
     */
    @RequestMapping("update")
    public String update(Info info, MultipartFile icon, MultipartFile icon2) {
        if (!icon2.isEmpty())
            info.setCcpath(saveFile(icon2));
        if (!icon.isEmpty())
            info.setXdtpath(saveFile(icon));
        infoMapper.updateByPrimaryKeySelective(info);
        check(info);
        return refresh();
    }

    @GetMapping("add")
    public String add() {
        Life life = lifeMapper.selectByUser(sessionUser().getId());
        Personal personal = personalMapper.selectByUser(sessionUser().getId());
        if (life != null && personal != null)
            return "info/add";
        else {
            throw new RuntimeException("请先完善生活档案和个人档案");
        }
    }

    /**
     * 发表建议
     *
     * @param info
     * @return
     */
    @RequestMapping("remark")
    public String remark(Info info) {
        infoMapper.updateByPrimaryKey(info);
        return refresh();
    }

    @PostMapping("add")
    public String add(Info info, MultipartFile icon, MultipartFile icon2) {
        info.setCcpath(saveFile(icon2));
        info.setXdtpath(saveFile(icon));
        info.setAddtime(new Date());
        info.setUserid(sessionUser().getId());

        Life life = lifeMapper.selectByUser(sessionUser().getId());
        Personal personal = personalMapper.selectByUser(sessionUser().getId());
        //计算分数
        if (personal.getSex().equals("男")) {
            int s3 = 0;
            if (life.getXy().equals("是")) s3 = 1;
            info.setS3(s3);

            int s4 = 0;
            if (info.getXyss() < 120) s4 = -2;
            if (info.getXyss() >= 120 && info.getXyss() < 130) s4 = 0;
            if (info.getXyss() >= 130 && info.getXyss() < 140) s4 = 1;
            if (info.getXyss() >= 140 && info.getXyss() < 160) s4 = 2;
            if (info.getXyss() >= 160 && info.getXyss() < 180) s4 = 5;
            if (info.getXyss() >= 180) s4 = 8;
            info.setS4(s4);

            int s6 = 0;
            if (personal.getTnb().equals("是")) s6 = 1;
            info.setS6(s6);
        } else {
            int s3 = 0;
            if (life.getXy().equals("是")) s3 = 2;
            info.setS3(s3);

            int s4 = 0;
            if (info.getXyss() < 120) s4 = -2;
            if (info.getXyss() >= 120 && info.getXyss() < 130) s4 = 0;
            if (info.getXyss() >= 130 && info.getXyss() < 140) s4 = 1;
            if (info.getXyss() >= 140 && info.getXyss() < 160) s4 = 2;
            if (info.getXyss() >= 160 && info.getXyss() < 180) s4 = 3;
            if (info.getXyss() >= 180) s4 = 4;
            info.setS4(s4);

            int s6 = 0;
            if (personal.getTnb().equals("是")) s6 = 2;
            info.setS6(s6);
        }

        int s1 = 0;
        if (personal.getAge() >= 40 && personal.getAge() <= 44) s1 = 1;
        if (personal.getAge() >= 45 && personal.getAge() <= 49) s1 = 2;
        if (personal.getAge() >= 50 && personal.getAge() <= 54) s1 = 3;
        if (personal.getAge() >= 55 && personal.getAge() <= 59) s1 = 4;
        info.setS1(s1);

        int s2 = 0;
        if (info.getTz() >= 24 && info.getTz() <= 28) s2 = 1;
        if (info.getTz() >= 28) s2 = 2;
        info.setS2(s2);

        int s5 = 0;
        if (info.getDgc() >= 5.2) s5 = 1;
        info.setS5(s5);

        info.setScore(info.getS1() + info.getS2() + info.getS3() + info.getS4() + info.getS5() + info.getS6());

        String icvd = "0.3";
        if (info.getScore() == 0) icvd = "0.5";
        if (info.getScore() == 1) icvd = "0.6";
        if (info.getScore() == 2) icvd = "0.8";
        if (info.getScore() == 3) icvd = "1.1";
        if (info.getScore() == 4) icvd = "1.5";
        if (info.getScore() == 5) icvd = "2.1";
        if (info.getScore() == 6) icvd = "2.9";
        if (info.getScore() == 7) icvd = "3.9";
        if (info.getScore() == 8) icvd = "5.4";
        if (info.getScore() == 9) icvd = "7.3";
        if (info.getScore() == 10) icvd = "9.7";
        if (info.getScore() == 11) icvd = "12.8";
        if (info.getScore() == 12) icvd = "16.8";
        if (info.getScore() == 13) icvd = "21.7";
        if (info.getScore() == 14) icvd = "27.7";
        if (info.getScore() == 15) icvd = "35.3";
        if (info.getScore() == 16) icvd = "44.3";
        if (info.getScore() >= 17) icvd = "52.6";
        info.setIcvd(icvd);

        infoMapper.insertSelective(info);
        check(info);


        //发送消息建议

        String content = "";
        if (personal.getSex().equals("男")) {
            if (info.getScore() == 1) content="123";
        }else{
            if (info.getScore() == 1) content="123456";
        }


        Message message1 = new Message();
        message1.setAddtime(new Date());
        message1.setContent(content);
        message1.setTitle("缺血性心血管病风险评估建议");
        message1.setSendid(1);
        message1.setUserid(sessionUser().getDoctor());
        message1.setStatus("no");
        messageMapper.insertSelective(message1);

        return "redirect:list";
    }

    /**
     * 校验用户数据
     * 如果有异常数据   就给负责医生发送消息
     *
     * @param info
     */
    public void check(Info info) {
        String message = "";
        if (info.getXyss() > 140 || info.getXyss() < 90) message += " 血压（收缩压）超过正常范围；";
        if (info.getXysz() > 90 || info.getXysz() < 60) message += "血压（舒张压）超过正常范围；";
        if (info.getXl() > 100 || info.getXl() < 60) message += "心率超过正常范围；";
        if (info.getXt() > 6.11 || info.getXt() < 3.89) message += "血糖超过正常范围；";
        if (info.getBmi() > 23.9 || info.getBmi() < 18) message += "BMI超过正常范围；";
        if (info.getSlz() > 2 || info.getSlz() < 1) message += "左眼视力超过正常范围；";
        if (info.getSly() > 2 || info.getSly() < 1) message += "右眼视力超过正常范围；";
        if (!"正常".equals(info.getBsnl())) message += "辨色能力不正常；";
        if (!"正常".equals(info.getXz())) message += "心脏不正常；";
        if (!"正常".equals(info.getFz())) message += "肺脏不正常；";
        if (!"正常".equals(info.getSz())) message += "四肢不正常；";
        if (!"正常".equals(info.getLb())) message += "淋巴不正常；";
        if (!"正常".equals(info.getJzx())) message += "甲状腺不正常；";
        if (!"正常".equals(info.getXj())) message += "嗅觉不正常；";
        if (!"正常".equals(info.getXdt())) message += "血常规不正常；";
        if (!"正常".equals(info.getCc())) message += "彩超不正常；";
        if (message.length() > 0) {
            Message message1 = new Message();
            message1.setAddtime(new Date());
            message1.setContent("用户【" + sessionUser().getName() + "】" + message);
            message1.setSendid(sessionUser().getId());
            message1.setUserid(sessionUser().getDoctor());
            message1.setStatus("no");
            messageMapper.insertSelective(message1);
        }

    }

}
